﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BO;
using UIControls;
using UI;
using UI.Core;
using System.Data.SqlClient;
using System.Dynamic;
namespace UI
{
    public partial class DBAForm : ToolFormBase, IMenuForm
    {
        public DBAForm()
        {
            InitializeComponent();   
        }

        private void CreateDataBase(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            this.btnOK.Enabled = false;
            try
            {
                BackupDatabase();
               // var db = new MyDb("CREATE");
                MessageBox.Show("OK");
            }
            catch (ExceptionEx ep)
            {
                ExcptionHandler.ShowExcption(ep);
            }
            finally
            {
                this.btnOK.Enabled = true;
                Cursor = Cursors.Default;
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
           
           
            Cursor = Cursors.WaitCursor;
            this.btnOK.Enabled = false;
            try
            {
                var sqlTxt = txtSql.Text.TrimStart();
                if (sqlTxt.Equals("Create", StringComparison.CurrentCultureIgnoreCase))
                {
                    btnCreate.Visible = !btnCreate.Visible;
                    return;
                }
                if (sqlTxt.StartsWith("select", StringComparison.CurrentCultureIgnoreCase))
                {
                    var dt =  BinDataTableAdapter.GetDataTable(CommandType.Text,sqlTxt);
                    txtMsg.Text = string.Format("结果行数{0}.", dt.Rows.Count);
                    grid.SetObjects(dt);
                    if (dt.Columns.Contains("Amount"))
                    {
                       // var totalAmount = dt.Compute("Sum(Amount)", "");
                      //  txtMsg.Text += Environment.NewLine + string.Format("金额合计{0}.", totalAmount);
                    }

                }
                else
                {
                    SQLExcuteAdapter.Execute(sqlTxt);
                    int rows = 0;// DBHelper.ExecuteCommand(sqlTxt);
                    txtMsg.Text = string.Format("影响行数{0}.", rows);
                }
            }
            catch (ExceptionEx ex)
            {
                ExcptionHandler.ShowExcption(ex);
            }
            finally
            {
                this.btnOK.Enabled = true;
                Cursor = Cursors.Default;
            }

        }

        private void DBAForm_Load(object sender, EventArgs e)
        {
            this.btnCreate.Visible = false;
            if (!GlobalVar.User.IsSystemUser)
                this.Enabled = false;
        }

        private void DBAForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.Alt | Keys.G))
            {
                this.btnCreate.Visible = true;
            }
        }

        void BackupDatabase()
        {
            try
            {
                SaveFileDialog _SaveFileDialog = new SaveFileDialog();         //保存的文件目录路径       
                
                _SaveFileDialog.Title = "请选择备份保存的目录";
                _SaveFileDialog.Filter = "(*.Bak)|*.Bak;|(All Files)|*.*";
                if (_SaveFileDialog.ShowDialog() == DialogResult.OK)
                {

                    string _FolderPath = _SaveFileDialog.FileName;

                    SQLExcuteAdapter.Execute("BACKUP DATABASE " + GlobalVar.DatabaseName + " TO DISK = '" + _FolderPath + "' ");

                    this.Cursor = Cursors.Arrow;

                    MessageBox.Show("备份数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                this.Cursor = Cursors.Arrow;

            }
            catch (ExceptionEx error)
            {
                this.Cursor = Cursors.Arrow;
                MessageBox.Show("异常:" + error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Arrow;
        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            BackupDatabase();
        }

           private void btnRestory_Click(object sender, System.EventArgs e)
        {
            if(MessageBox.Show("该操作将数据覆盖!!\n\n如果选择[是],将原来的数据覆盖\n\n如果选择[否],将取消恢复","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.No)
                return;
            if(MessageBox.Show("请再次确认,该操作不能恢复!!\n\n如果选择[是],将原来的数据覆盖\n\n如果选择[否],将取消恢复","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)==DialogResult.No)
                return;
            this.Cursor = Cursors.WaitCursor;
 
               
            try
            {
                   var _SaveFileDialog = new OpenFileDialog();         //保存的文件目录路径       
                _SaveFileDialog.Title = "请选择备份保存的目录";
                _SaveFileDialog.Filter = "(*.Bak)|*.Bak;|(All Files)|*.*";
               if (_SaveFileDialog.ShowDialog() != DialogResult.OK)
                return;

               // SqlCommand _Comm = new SqlCommand(@"restore filelistonly from disk='"mailto:+_FolderPath+@%22\%22+_DBPath+@%22.bak'%22,_Conn);//获得原来的逻辑名称以及物理路径
              //  SqlDataReader _Reader =DBHelper.GetReader("restore filelistonly from disk='"+_SaveFileDialog.FileName+"'");
               SqlDataReader _Reader=null;
                string[]  _LogName = new string[2];//获得逻辑名称
                string[]  _PhiPath = new string[2];//获得物理路径
                int j = 0;
                while(_Reader.Read())
                {
                    _LogName[j] = (string)_Reader.GetValue(0);
                    _PhiPath[j] = (string)_Reader.GetValue(1);
                    j = j+1;
                }
                _Reader.Close();
                MessageBox.Show(_LogName[0]);
                        
                //执行数据库恢复脚本
              var txt ="RESTORE DATABASE [" +GlobalVar.DatabaseName + "]   FROM DISK = '" + _SaveFileDialog.FileName + "' With Move '"+ _LogName[0] +
                    "' TO '" +_PhiPath[0]+ "',  Move '" + _LogName[1] + "' TO '" + _PhiPath[1]+ "'";
             // DBHelper.Connection.Database = "Master";
              //DBHelper.ExecuteCommand(txt);
                this.Cursor = Cursors.Arrow;
                MessageBox.Show("数据恢复成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
             
                this.Cursor = Cursors.Arrow;
 
            }
            catch(ExceptionEx error)
            {
                this.Cursor = Cursors.Arrow;
                MessageBox.Show("异常:"+error.Message,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            } 
        }

           private void btnExport_Click(object sender, EventArgs e)
           {
               OnExport();
           }
           virtual protected void OnExport()
           {
               var dt =this.grid.GenerateDataTable();
               var excel = new ExcelAdapter();
               excel.SaveExcel(dt, "", this.Text, this.Text);
           }

           private void btnTest_Click(object sender, EventArgs e)
           {
               var bill = new Billing();
               bill.ID = 1;
               bill.Get();
           }

          

    }
}

